import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { CreateRoomDto } from './dto/room.dto';
import { MongoService } from 'src/mongo/mongo.service';
import { Server } from 'socket.io';

@Injectable()
export class RoomService {
  constructor(private mongoService: MongoService) {}
  async createRoom(data: CreateRoomDto) {
    const isExist = await this.mongoService.roomExist({
      room_name: data.room_name,
      school: data.school,
    });
    if (!isExist) {
      return this.mongoService.createRoom(data);
    } else {
      throw new HttpException('房间已存在', HttpStatus.FOUND);
    }
  }
  async joinRoom(
    socket: Server,
    data: {
      room_id: string;
      random: string;
      user_name: string;
      socket_id: string;
    },
  ) {
    const res = await this.mongoService.joinRoom(data);
    if (res.exist) {
      const client = socket.sockets.sockets.get(res.res.socket_id);
      console.log('被踢', res.res.socket_id);
      socket.sockets.sockets.forEach((item) => {
        console.log('用户', item.id);
      });
      if (client) {
        client.emit('kicked', { message: '已在其他设备登陆' });
        client.disconnect(true);
      }
    }
    return res;
  }
  async getRoomUser(room_id: string) {
    return await this.mongoService.getUsers(room_id);
  }
  async exitRoom(room_id: string, user: { random: string; user_name: string }) {
    return this.mongoService.exitRoom(room_id, user);
  }
}
